import * as React from "react";

export interface DancingNumProps {
  number: number;
}

export interface DancingNumState {}

class DancingNum extends React.Component<DancingNumProps, DancingNumState> {
  state = { currentNumber: 0 };
  rafId: number | null = null;
  startDance = () => {
    this.rafId = requestAnimationFrame(this.dance);
  };

  stopDance = () => {
    if (this.rafId) {
      cancelAnimationFrame(this.rafId);
    }
  };
  componentWillReceiveProps() {
    this.stopDance();
    this.startDance();
  }
  dance = () => {
    let { currentNumber } = this.state;

    this.setState({
      currentNumber:
        currentNumber < this.props.number
          ? Math.min(this.props.number, currentNumber + 1)
          : Math.max(this.props.number, currentNumber - 1),
    });
    if (this.state.currentNumber !== this.props.number) {
      this.startDance();
    }
  };
  render() {
    return this.state.currentNumber;
  }
}

export default DancingNum;
